import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import Taro, { useDidShow } from '@tarojs/taro';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import gotFlag from '@/giftCardSubPack/images/couponCenter/got.png';
import hotShop from '@/giftCardSubPack/images/couponCenter/hot.png';
import hotTakeOut from '@/giftCardSubPack/images/couponCenter/hot2.png';
import { sourceUrl } from '@/config';
import emptyCoupon from '@/giftCardSubPack/images/coupon/emptyCoupon.png';
import title from '@/giftCardSubPack/images/couponCenter/title.png';
import { ProductType } from '@/dataTransfer/coupon.js';
import { WrapPageLoadLoading } from '@/components/PageLoadLoading';
import classNames from 'classnames';
import utils from '@/utils/index';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import './index.scss';

const debounce = (fn, delay) => {
  let runFlagDebounce = true;

  let timer = null;
  return async (...args) => {
    clearTimeout(timer);
    if (runFlagDebounce) {
      await fn.apply(this, args);
      runFlagDebounce = false;
    }
    timer = setTimeout(() => {
      runFlagDebounce = true;
    }, delay);
  };
};

let statusBarHeight = Taro.$statusBarHeight;
if (Taro.$isH5) {
  statusBarHeight = 44;
}

const goLogin = () => {
  Taro.navigateTo({
    url: '/pages/other/login/index',
  });
};

const EmptyCoupon = () => {
  return (
    <View className="no-coupon-wrap">
      <View className="no-coupon">
        <Image src={emptyCoupon} className="empty-coupon" />
        {/* <Text className="desc">暂无可用优惠券</Text> */}
      </View>
    </View>
  );
};

const CouponItemShop = ({ item, doAction }) => {
  const {
    isHot,
    sourceType,
    productType,
    minAmount,
    discountAmount,
    stock,
    isReceive,
    type,
    products,
    categorys = [],
    couponId,
    orgName,
  } = item;
  return (
    <View className="coupon-item-shop">
      <View className="left">
        <View className="line">
          {isHot == 1 && <Image className="hot" src={hotShop} />}
          <Text className="title">
            {(sourceType == 1
              ? orgName +
                (productType === ProductType.all
                  ? '全部'
                  : categorys.length > 0
                  ? '【' + categorys.join('、') + '】' + '类'
                  : '部分')
              : '商城' +
                (productType === ProductType.all
                  ? '全品类'
                  : '【' + categorys.join('、') + '】' + '类')) + '商品可用'}
          </Text>
        </View>
        <View className="pros">
          {products &&
            products.length > 0 &&
            products.slice(0, 3).map((product, index) => (
              <View className="product" key={couponId + 'product' + index}>
                <Image
                  className="img"
                  src={product?.url?.indexOf('http') === 0 ? product.url : sourceUrl + product.url}
                ></Image>
                <Text className="price">￥{product.price}</Text>
              </View>
            ))}
        </View>
      </View>
      <View className="right">
        {type == 1 && (
          <View className="less customePageStyle">
            <Text className="unit">￥</Text>
            {discountAmount}
          </View>
        )}
        {type == 3 && (
          <View className="less customePageStyle">
            {discountAmount}
            <Text className="unit">折</Text>
          </View>
        )}
        <View className="condition customePageStyle">
          {minAmount > 0 ? '满' + minAmount + '元可用' : '无门槛'}
        </View>
        <View
          className={classNames('btn customePageBackgroundStyle', {
            stock: !stock,
            'has customePageStyle customePageBorderStyle': isReceive,
          })}
          onClick={() => {
            ((stock > 0 && isReceive == false) || isReceive == true) && doAction(item);
          }}
        >
          {stock <= 0 && isReceive == false && '已抢光'}
          {isReceive == true && '去使用'}
          {stock > 0 && isReceive == false && '立即领取'}
        </View>
      </View>
      {isReceive == true && <Image className="gotFlag" src={gotFlag}></Image>}
    </View>
  );
};

const CouponItemTakeOut = ({ item, doAction }) => {
  const {
    isHot,
    sourceType,
    productType,
    minAmount,
    discountAmount,
    stock,
    isReceive,
    type,
    logoUrl,
    categorys = [],
    orgName,
    timeType,
    effectiveDay,
    startTime,
    endTime,
  } = item;
  return (
    <View className="coupon-item-takeout">
      {isHot == 1 && <Image className="hot" src={hotTakeOut} />}
      <View className="left">
        <Image className="logo" src={logoUrl} />
      </View>
      <View className="middle">
        <View className="title">
          {sourceType == 1
            ? '【' + orgName + '】' + '外卖券'
            : '外卖频道' +
              (productType === ProductType.all
                ? '全品类'
                : categorys.length > 0
                ? '【' + categorys.join('、') + '】' + '类'
                : '') +
              '可用'}
        </View>
        <View className="condition">{minAmount > 0 ? '满' + minAmount + '元可用' : '无门槛'}</View>
        <View className="useCon">
          {sourceType == 1 && '限指定商家外卖订单使用'}
          {sourceType == 0 && productType === ProductType.all && '外卖全品类可用'}
          {sourceType == 0 && productType !== ProductType.all && '外卖某某品类可用'}
        </View>
        <View className="time">
          {timeType == 1
            ? startTime.split(' ')[0] + '~' + endTime.split(' ')[0]
            : effectiveDay + '天后生效'}
        </View>
      </View>
      <View className="right">
        {type == 2 && (
          <View className="less customePageStyle">
            <Text className="unit">￥</Text>
            {discountAmount}
          </View>
        )}
        {type == 4 && (
          <View className="less customePageStyle">
            {discountAmount}
            <Text className="unit">折</Text>
          </View>
        )}
        <View
          className={classNames('btn customePageBackgroundStyle', {
            stock: stock <= 0,
            'has customePageStyle customePageBorderStyle': isReceive,
          })}
          onClick={() => {
            ((stock > 0 && isReceive == false) || isReceive == true) && doAction(item);
          }}
        >
          {stock <= 0 && isReceive == false && '已抢光'}
          {isReceive == true && '去使用'}
          {stock > 0 && isReceive == false && '立即领取'}
        </View>
      </View>
      {isReceive == true && <Image className="gotFlag" src={gotFlag}></Image>}
    </View>
  );
};

const CouponCenter = ({
  dispatch,
  loading,
  appConfiguration,
  couponList,
  couponListFinished,
  pendingCoupon,
}) => {
  useShowLoading(loading, ['giftCard/getHotCouponList', 'giftCard/getCouponList']);

  const [updateFactor, setUpdateFactor] = useState();

  const handleUseCoupon = (item) => {
    const { type, sourceType, minAmount, discountAmount, couponId, id, orgId, merchantId } = item;
    if (type == 1 || type == 3) {
      //商家券--券适用商品列表
      let name =
        minAmount > 0
          ? type == 1
            ? `满${minAmount}减${discountAmount}`
            : `满${minAmount}打${discountAmount}折`
          : '无门槛';
      Taro.navigateTo({
        url: `/giftCardSubPack/couponProducts/index?configId=${id}&couponId=${couponId}&sourceType=${sourceType}&name=${name}`,
      });
    } else if (type == 2 || type == 4) {
      //外卖券
      if (sourceType == 0) {
        //平台--商户列表页
        Taro.navigateTo({
          url: `/giftCardSubPack/couponShopList/index?configId=${id}&couponId=${couponId}&sourceType=${sourceType}`,
        });
      } else if (sourceType == 1) {
        //商家--商家外卖详情页
        Taro.navigateTo({
          url:
            '/mainSubPack/takeOutShop/index' + '?' + 'orgId=' + orgId + '&merchantId=' + merchantId,
        });
      }
    }
  };

  const doAction = debounce((item) => {
    // 未登录时, 领取优惠券数据存储, 用于登录后直接领取优惠券
    if (item.isReceive == false) {
      dispatch({
        type: 'giftCard/setPendingCoupon',
        payload: item,
      });
    }

    if (!utils.getToken()) {
      goLogin();
      return;
    }

    if (item.isReceive == false) {
      return dispatch({
        type: 'giftCard/createCoupon',
        payload: {
          sourceType: item.sourceType,
          id: item.id,
        },
      })
        .then(({ results, couponId } = {}) => {
          if (results) {
            return Taro.showToast({
              title: results,
              icon: 'none',
            });
          }

          const index = couponList.findIndex((obj) => {
            return obj.id === item.id;
          });

          if (index == -1) {
            return;
          }

          if (index != -1) {
            const temp = [...couponList];

            temp[index].isReceive = true;
            temp[index].couponId = couponId;

            dispatch({
              type: 'giftCard/setCouponListPure',
              payload: temp,
            });
          }

          Taro.showToast({
            title: '领取成功',
            icon: 'none',
          });

          // 领取成功, 清除待领取状态
          dispatch({
            type: 'giftCard/setPendingCoupon',
            payload: undefined,
          });
        })
        .catch((e) => {
          console.warn(e);
          Taro.showToast({
            title: '领取失败',
            icon: 'none',
          });
        });
    } else if (item.isReceive == true) {
      handleUseCoupon(item);
    }
  }, 1000);

  const goBack = () => {
    Taro.navigateBack();
  };

  const [curType, setCurType] = useState();
  const [hasTab, setHasTab] = useState(false);
  const [nodeal, setNodeal] = useState(false);

  const getAppConfiguration = () => {
    dispatch({
      type: 'giftCard/getAppConfiguration',
    });
  };

  const getCouponList = () => {
    dispatch({
      type: 'giftCard/getCouponList',
      payload: {
        pageSize: 20,
        type: curType,
        updateFactor,
      },
    });
  };

  const clearCouponList = () => {
    dispatch({
      type: 'giftCard/resetCouponList',
      payload: {},
    });
  };

  const handleScrollToLower = debounce(() => {
    if (couponListFinished || !curType) {
      return;
    }
    getCouponList();
  }, 2000);

  useEffect(() => {
    getAppConfiguration();
  }, []);

  useDidShow(async () => {
    // 领取登录前未领取的优惠券
    if (pendingCoupon && utils.getToken()) {
      await doAction(pendingCoupon);

      // 清除待领取状态
      dispatch({
        type: 'giftCard/setPendingCoupon',
        payload: undefined,
      });
    }

    // 重新设置 下面商城券和外卖券的 更新因子
    setUpdateFactor(Date.now());
  });

  // 清除待领取状态
  useEffect(() => {
    return () => {
      dispatch({
        type: 'giftCard/setPendingCoupon',
        payload: undefined,
      });
    };
  }, []);

  useEffect(() => {
    if (!appConfiguration) {
      return;
    }
    if (appConfiguration?.supportedTakeAway == 1 && appConfiguration?.supportedMall == 1) {
      setHasTab(true);
      setNodeal(false);
      setCurType(2);
    } else if (appConfiguration?.supportedTakeAway == 1 || appConfiguration?.supportedMall == 1) {
      setHasTab(false);
      setNodeal(false);
      appConfiguration?.supportedMall == 1 && setCurType(1);
      appConfiguration?.supportedTakeAway == 1 && setCurType(2);
    } else {
      setHasTab(false);
      setNodeal(true);
    }
  }, [appConfiguration]);

  useEffect(() => {
    if (!updateFactor) {
      return;
    }
    if (!curType) {
      return;
    }

    getCouponList();
  }, [curType, updateFactor]);

  return (
    <View className="totalPage_couponCenter">
      <View className="fontPage">
        <ScrollView
          className={['contentPage', Taro.$isH5 && 'bgPosition'].join(' ')}
          scrollY
          lowerThreshold={240}
          onScrollToLower={handleScrollToLower}
        >
          <View className={['couponCenter', Taro.$isH5 && 'h5Position'].join(' ')}>
            {Taro.$isH5 && (
              <View className="topPage" style={{ paddingTop: statusBarHeight + 'px' }}>
                <View className="topBarLine H5">
                  <Image className="topBar" src={title} />
                </View>
              </View>
            )}

            <View
              className={'coupon-tab customePageBackgroundStyle' + (hasTab ? ' showCouponTab' : '')}
            >
              <View
                className={classNames('item', {
                  'active customePageBorderStyle': curType === 2,
                })}
                onClick={() => {
                  curType !== 2 && clearCouponList();
                  setCurType(2);
                }}
              >
                <View
                  className={classNames('top', {
                    customePageStyle: curType === 2,
                  })}
                >
                  外卖券
                </View>
              </View>

              <View
                className={classNames('item', {
                  'active customePageBorderStyle': curType === 1,
                })}
                onClick={() => {
                  curType !== 1 && clearCouponList();
                  setCurType(1);
                }}
              >
                <View
                  className={classNames('top', {
                    customePageStyle: curType === 1,
                  })}
                >
                  商城券
                </View>
              </View>
            </View>

            {couponList?.map((item) => {
              if (curType === 2) {
                return (
                  <CouponItemTakeOut
                    key={item.id}
                    doAction={doAction}
                    item={item}
                  ></CouponItemTakeOut>
                );
              } else {
                return (
                  <CouponItemShop key={item.id} doAction={doAction} item={item}></CouponItemShop>
                );
              }
            })}

            {couponListFinished && couponList.length > 8 && (
              <View className="end">- 我是有底线的 -</View>
            )}

            {(!couponList || couponList.length === 0 || nodeal) && <EmptyCoupon />}
          </View>
        </ScrollView>
      </View>
    </View>
  );
};

export default connect(({ giftCard, loading }) => ({
  loading,
  appConfiguration: giftCard.appConfiguration,
  couponList: giftCard.couponList,
  couponListFinished: giftCard.couponListFinished,
  pendingCoupon: giftCard.pendingCoupon,
}))(WrapPageLoadLoading(CouponCenter));
